﻿using soma.Helpers;
using soma.Models.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace soma.Services
{
    public class PhotosRepository : Repository
    {
        private static PhotosRepository instance = null;
        private const string PHOTOS_RESOURCES_DICTIONARY = "PhotosResourcesDictionary";

        protected override string CacheKeysResources
        {
            get
            {
                return PHOTOS_RESOURCES_DICTIONARY;
            }
        }

        // Keep photos by tag and ordered most current date. Keep a maximum number of photos in cache.
        // If new photos are requested we make a request to get new photos that are more recent and remove some of the old ones
        // If the latest photo is more recent that X time we return that list
        private PhotosRepository()
        {
   //         lock (contextResourcesLocker)
            {
                context = HttpContext.Current;

                if (context != null)
                {
                    if (context.Cache[CacheKeysResources] == null)
                    {
                        context.Cache[CacheKeysResources] = new Dictionary<string, List<IResource>>();
                    }

                    if (context.Cache[CacheKeysTags] == null)
                    {
                        context.Cache[CacheKeysTags] = new Dictionary<string, List<string>>();
                    }
                }
            }
        }

        public static PhotosRepository Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        instance = new PhotosRepository();
                    }
                }

                return instance;
            }
        }

        public List<PhotoResource> GetPhotos()
        {
            List<PhotoResource> photoResources = new List<PhotoResource>();

            lock (contextResourcesLocker)
            {
                Dictionary<string, List<PhotoResource>> dictPhotoResources = context.Cache[CacheKeysResources] as Dictionary<string, List<PhotoResource>>;
                foreach (List<PhotoResource> photosByTag in dictPhotoResources.Values)
                {
                    photoResources.AddRange(photosByTag);
                }
            }

            return photoResources;
        }

        public void AddPhotoByTag(string tag, PhotoResource photoResource)
        {

        }

        public int GetNoPhotosByTag(string tag)
        {
            Dictionary<string, List<PhotoResource>> dictPhotoResources = context.Cache[CacheKeysResources] as Dictionary<string, List<PhotoResource>>;
            /*if (dictPhotoResources.ContainsKey(tag))
            { 

            }*/

            return 1;
        }
    }
}